package com.becca.cake.controller.voucher;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.becca.cake.core.common.BaseAction;
import com.becca.cake.core.common.PagingBean;
import com.becca.cake.core.exception.CommonExceptionHandle;
import com.becca.cake.model.voucher.VoucherAdvertModel;
import com.becca.cake.model.voucher.VoucherModel;
import com.becca.cake.model.voucher.VoucherOrderDetailsModel;
import com.becca.cake.model.voucher.VoucherOrderModel;
import com.becca.cake.model.voucher.VoucherUserPaymentsModel;
import com.becca.cake.service.voucher.IVoucherService;
import com.becca.cake.util.DateUtils;
import com.becca.cake.util.JsonUtil;

/**
 * 抵用券Controller
 * @copyright  尊星(上海)信息科技有限公司
 * @author mouwanming
 * @date 2016年9月6日 下午6:12:37
 */
@Controller
@RequestMapping("/voucherManager")
public class VoucherAction extends BaseAction{
	private final static Log logger = LogFactory.getLog(VoucherAction.class);
	
	@Autowired
	IVoucherService iVoucherService;
	/**
     * 广告查询
     * @param voucherAdvertModel
     * @return
     */
     @RequestMapping(value = "/selectVoucherAdverts", method = RequestMethod.POST)
     @ResponseBody
	public String selectVoucherAdverts(VoucherAdvertModel voucherAdvertModel,String formStartDate,String formEndDate){
		PagingBean page = getInitPagingBean();
		Map<String, Object> map = new HashMap<String, Object>();
        map.put("voucherAdvertModel", voucherAdvertModel);
        map.put("pagingBean", page);
        map.put("formStartDate", formStartDate);
        map.put("formEndDate", formEndDate);
        try {
        	// stmp1:获取广告数据
			List<VoucherAdvertModel> list = this.iVoucherService.selectVoucherAdverts(map);
			// stmp2:获取广告总条数
			Long count = this.iVoucherService.selectVoucherAdvertsCount(map);
			return JsonUtil.writeObjectPageJSON(list, count);
		} catch (Exception e) {
			return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
		}
	}
	
	/**
     * 添加或修改广告信息
     * @author mouwanming
     * @return
     */
     @RequestMapping(value = "/insertOrUpdateVoucherAdvert", method = RequestMethod.POST)
     @ResponseBody
	public String insertOrUpdateVoucherAdvert(HttpServletRequest request, VoucherAdvertModel voucherAdvertModel){
	//step1:获取图片file
	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile files = multipartRequest.getFile("upload");
    try {
		this.iVoucherService.insertOrUpdateVoucherAdvert(voucherAdvertModel, files, getTempFoderPath(), this.getUserSeesion());
		return JsonUtil.returnJsonSuccess("操作广告信息成功!");
	} catch (Exception e) {
		return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
	}
	}
	
	
	/**
     * 根据id查询广告对象
     * @param advertId
     * @return
     */
    @RequestMapping(value = "/selectVoucherAdvertById", method = RequestMethod.POST)
    @ResponseBody
    public String selectVoucherAdvertById(@RequestParam("advertId") Integer advertId) {
        try {
            //step1:请求参数
            VoucherAdvertModel voucherAdvertModel = this.iVoucherService.selectVoucherAdvertById(advertId);
            return JsonUtil.writeObjectFormJSON(voucherAdvertModel);
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }
    
    /**
     * 根据id启用或禁用广告对象
     * @param advertId
     * @return
     */
    @RequestMapping(value = "/updateAdvStatusById", method = RequestMethod.POST)
    @ResponseBody
    public String updateAdvStatusById(@RequestParam(value = "advertId", required = false) Integer advertId,
                                      @RequestParam(value = "status", required = false) String status) {
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("advertId", advertId);
            paramMap.put("status", status);
            paramMap.put("userName", this.getUserSeesion().getTrueName());
            this.iVoucherService.updateAdvStatusById(paramMap);
            return JsonUtil.returnJsonSuccess("操作广告信息成功!");
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }
    
    /**
     * 批量修改Order排序列
     * @param advertId
     * @return
     */
    @RequestMapping(value = "/updateVoucherOrders", method = RequestMethod.POST)
    @ResponseBody
    public String updateVoucherOrders(@RequestParam(value = "jsonList", required = false)String jsonList) {
        try {
            this.iVoucherService.updateVoucherOrders(jsonList);
            return JsonUtil.returnJsonSuccess("操作广告信息成功!");
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }
	
    /**
     * 查询抵用券流水数据
     * @param voucherPaymentModel
     * @return
     */
    @RequestMapping(value = "/selectVoucherPayments", method = RequestMethod.POST)
    @ResponseBody
    public String selectVoucherPayments(VoucherUserPaymentsModel voucherUserPaymentsModel) {
        PagingBean page = getInitPagingBean();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("voucherUserPaymentsModel", voucherUserPaymentsModel);
        map.put("pagingBean", page);
        try {
            // stmp1:查询抵用券流水数据
            List<VoucherUserPaymentsModel> list = this.iVoucherService.selectVoucherPayments(map);
            // stmp2:获取抵用券流水总数
            Long count = this.iVoucherService.selectVoucherPaymentsCount(map);
            return JsonUtil.writeObjectPageJSON(list, count);
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }

    /**
     * 查询抵用券数据
     * @param voucherModel
     * @return
     */
    @RequestMapping(value = "/selectVoucher", method = RequestMethod.POST)
    @ResponseBody
    public String selectVoucher(VoucherModel voucherModel, 
    		@RequestParam(value = "existall", required = false) String existall,
            @RequestParam(value = "statusArr", required = false) String statusArr) {

        Map<String, Object> map = new HashMap<String, Object>();
        PagingBean page = getInitPagingBean();
        map.put("pagingBean", page);
        map.put("voucherModel", voucherModel);
        try {
            // stmp1:查询商品数据
            List<VoucherModel> list = this.iVoucherService.selectVoucher(map);
            if ("true".equals(existall)) {
            	VoucherModel s = new VoucherModel();
                s.setVoucherName("全部");
                list.add(s);
            }
            // stmp2:获取商品总条数
            Long count = this.iVoucherService.selectVoucherCount(map);
            return JsonUtil.writeObjectPageJSON(list, count);
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }
	
    /**
     * 添加或修改抵用券信息
     * @author mouwanming
     * @return
     */
    @RequestMapping(value = "/insertOrUpdateVoucher", method = RequestMethod.POST)
    @ResponseBody
    public String insertOrUpdateVoucher(VoucherModel voucherModel) {
        
        try {
            this.iVoucherService.insertOrUpdateVoucher(voucherModel, this.getUserSeesion());
            return JsonUtil.returnJsonSuccess("保存抵用券成功!");
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }

    /**
     * 下架抵用券
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/updVoucherStatusById", method = RequestMethod.POST)
    @ResponseBody
    public String updVoucherStatusById(@RequestParam(value = "voucherId", required = false) Integer voucherId,
                                     @RequestParam(value = "voucherStatus", required = false) Integer voucherStatus) {
        try {
            this.iVoucherService.updVoucherStatusById(voucherId, voucherStatus, this.getUserSeesion()
                .getTrueName());
            return JsonUtil.returnJsonSuccess("下架抵用券成功！");
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }

    /**
     * 根据抵用券ID查询抵用券对象
     * @param voucherId
     * @return
     */
    @RequestMapping(value = "/selectVoucherById", method = RequestMethod.POST)
    @ResponseBody
    public String selectVoucherById(@RequestParam("voucherId") Integer voucherId) {
        try {
            VoucherModel voucherModel = this.iVoucherService.selectVoucherById(voucherId);
            return JsonUtil.writeObjectFormJSON(voucherModel);
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }

    /**
     * 批量修改抵用券Order排序列
     * @param voucherId
     * @return
     */
    @RequestMapping(value = "/updateVoucherOrder", method = RequestMethod.POST)
    @ResponseBody
    public String updateVoucherOrder(@RequestParam(value = "jsonList", required = false) String jsonList) {
        try {
            this.iVoucherService.updateVoucherOrder(jsonList, this.getUserSeesion().getTrueName());
            return JsonUtil.returnJsonSuccess("批量修改抵用券排序成功!");
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }
    
    
    /**
     * 查询订单信息
     * @param orderModel
     * @return
     */
    @RequestMapping(value = "/selectVoucherOrders", method = RequestMethod.POST)
    @ResponseBody
    public String selectVoucherOrders(@ModelAttribute VoucherOrderModel voucherOrderModel) {
        //step1:获取请求参数
        PagingBean page = getInitPagingSortBean();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("voucherOrderModel", voucherOrderModel);
        map.put("pagingBean", page);
        try {
            //step2:查询订单数据
            List<VoucherOrderModel> list = this.iVoucherService.selectVoucherOrders(map);
            Long count = this.iVoucherService.selectVoucherOrdersCount(map);
            //step3:返回订单数据
            return JsonUtil.writeObjectPageJSON(list, count);
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }
    
    /**
     * 修改订单数据
     * @param voucherOrderModel
     * @return
     */
    @RequestMapping(value = "/updateVoucherOrderD", method = RequestMethod.POST)
    @ResponseBody
    public String updateVoucherOrderD(VoucherOrderModel voucherOrderModel) {
        try {
        	voucherOrderModel.setUpdatedName(this.getUserSeesion().getTrueName());
            this.iVoucherService.updateVoucherOrder(voucherOrderModel);
            return JsonUtil.returnJsonSuccess("修改订单信息成功!");
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }

     /**
      * 根据orderId获取订单对象
      * @param orderId
      * @return
      */
     @RequestMapping(value = "/findVoucherOrderById", method = RequestMethod.POST)
     @ResponseBody
     public String findVoucherOrderById(@RequestParam(value = "orderId", required = false) Integer orderId) {
         try {
             VoucherOrderModel voucherOrderModel = this.iVoucherService.findVoucherOrderById(orderId);
             return JsonUtil.writeObjectFormJSON(voucherOrderModel);
         } catch (Exception e) {
             logger.error("获取订单对象失败!");
             return JsonUtil.returnJsonUnSuccess("获取订单对象失败!");
         }
     }

     /**
      * 根据订单编号查询订单详情
      * @param orderId
      * @return
      */
     @RequestMapping(value = "/queryOrderDetail", method = RequestMethod.POST)
     @ResponseBody
     public String queryOrderDetail(@RequestParam(value = "orderId", required = false) Integer orderId) {
         try {
             List<VoucherOrderDetailsModel> list = this.iVoucherService.selectVoucherDetailsByOrderId(orderId);
             return JsonUtil.writeObjectNoPageJSON(list);
         } catch (Exception e) {
             return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
         }
     }

     /**
      * 单个/批量修改订单状态
      * @return
      */
     @RequestMapping(value = "/updateVoucherOrderStatus", method = RequestMethod.POST)
     @ResponseBody
     public String updateVoucherOrderStatus(@RequestParam(value = "orderIds", required = false) String orderIds,
                                     @RequestParam(value = "orderStatus", required = false) String orderStatus,
                                     @RequestParam(value = "statusName", required = false) String statusName) {
         //step1:封装请求参数
         Map<String, Object> paramMap = new HashMap<String, Object>();
         paramMap.put("orderIds", orderIds);
         paramMap.put("orderStatus", orderStatus);
         paramMap.put("statusName", statusName);
         paramMap.put("userName", this.getUserSeesion().getTrueName());
         try {
             //step2:修改订单状态
             this.iVoucherService.updateVoucherOrderStatus(paramMap);
             return JsonUtil.returnJsonSuccess("操作订单状态成功!");
         } catch (Exception e) {
             return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
         }
     }
     

     /**
      * 单个修改订单状态,上传确认发货图
      * @return
      */
     @RequestMapping(value = "/insertVoucherOrderPicture", method = RequestMethod.POST)
     @ResponseBody
     public String insertVoucherOrderPicture(HttpServletRequest request, VoucherOrderModel voucherOrderModel,@RequestParam(value = "orderIds", required = false) String orderIds,
                                     @RequestParam(value = "orderStatus", required = false) String orderStatus,
                                     @RequestParam(value = "statusName", required = false) String statusName) {
    	//step1:获取图片file
  		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  	    MultipartFile files = multipartRequest.getFile("upload");
    	 //step1:封装请求参数
//         Map<String, Object> paramMap = new HashMap<String, Object>();
//         paramMap.put("orderIds", orderIds);
//         paramMap.put("orderStatus", orderStatus);
//         paramMap.put("statusName", statusName);
//         paramMap.put("userName", this.getUserSeesion().getTrueName());
         try {
        	 this.iVoucherService.insertVoucherOrderPicture(voucherOrderModel, files, getTempFoderPath(), this.getUserSeesion());
             //step2:修改订单状态
       //      this.iVoucherService.updateVoucherOrderStatus(paramMap);
             return JsonUtil.returnJsonSuccess("操作订单状态成功!");
         } catch (Exception e) {
             return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
         }
     }
     
     

     /**
      * 订单打印
      * @param orderId
      * @param model
      * @return
      */
     @RequestMapping(value = "/printOrder", method = RequestMethod.GET)
     public String printOrder(@RequestParam(value = "orderId", required = false) Integer orderId,
                              Model model) {
         try {
             //step1:订单信息
             VoucherOrderModel voucherOrderModel = this.iVoucherService.findVoucherOrderById(orderId);
             //step2:订单详情
             List<VoucherOrderDetailsModel> list = this.iVoucherService.selectVoucherDetailsByOrderId(orderId);
             model.addAttribute("voucherOrderModel", voucherOrderModel);
             model.addAttribute("orderList", list);
         } catch (Exception e) {
             return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
         }
         return "print/printVoucherOrder";
     }

     /**
      * 修改物流信息
      * @return
      */
     @RequestMapping(value = "/updateOrderLogisticsMessage", method = RequestMethod.POST)
     @ResponseBody
     public String updateOrderLogisticsMessage(@RequestParam(value = "logisticId", required = false) Integer logisticId,
                                               @RequestParam(value = "logisticMessage", required = false) String logisticMessage) {
         //step1:封装请求参数
         Map<String, Object> paramMap = new HashMap<String, Object>();
         paramMap.put("logisticId", logisticId);
         paramMap.put("logisticMessage", logisticMessage);
         paramMap.put("userName", this.getUserSeesion().getTrueName());
         try {
             //step1:修改物流信息
             this.iVoucherService.updateOrderLogisticsMessage(paramMap);
             return JsonUtil.returnJsonSuccess("修改物流信息成功!");
         } catch (Exception e) {
             return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
         }
     }
    
    
     /**
      * 批量导出订单数据
      * @param jsonList
      * @return
      */
     @SuppressWarnings({ "rawtypes", "unchecked" })
     @RequestMapping(value = "/exportOrdersToExcel", method = RequestMethod.GET)
     public void exportOrdersToExcel(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @RequestParam(value = "orderIds", required = false) String orderIds) {
         List list = this.iVoucherService.selectOrderExcelModel(orderIds);
         try {
             this.iVoucherService.exportOrdersToExcel(request, response, list);
         } catch (Exception e) {
             logger.error("订单数据导出excel失败!");
         }
     }
     
     
     /**
      * 交接单打印
      * @param orderIds
      * @param model
      * @return
      */
     @RequestMapping(value = "/printHandOverOrder", method = RequestMethod.GET)
     public String printHandOverOrder(@RequestParam(value = "orderIds", required = false) String orderIds,
                                      Model model) {
         //step1:封装请求参数
         try {
             //step2:获取订单列表对象
             List<VoucherOrderModel> orderList = this.iVoucherService.selectHandOverVoucherOrders(orderIds);
             model.addAttribute("orderList", orderList);
             model.addAttribute("userName", this.getUserSeesion().getTrueName());
             String nowDate = DateUtils.DateToString(new Date(),
                 DateUtils.FORMAT_yyyy_nian_M_yue_m_ri);
             model.addAttribute("nowDate", nowDate);
         } catch (Exception e) {
             return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
         }
         return "print/deliveryReceitp";
     }
    
    
    
}
